﻿#ifndef CUSTOMCEFVIEW_H
#define CUSTOMCEFVIEW_H
#include "../widgets.h"
#include <QScreen>
#include <QSharedPointer>
#include <QPointer>
#include <QCefView.h>

class CefViewWidget;
class BrowserDialog;

class S_WIDGETS_EXPORT CefViewDelegate
{
    friend class CefViewWidget;
public:
    CefViewDelegate() {}
    virtual ~CefViewDelegate() {}
    bool executeJavascript(int browserId, qint64 frameId, const QString& code, const QString& url);

    CefViewWidget* getCefViewWidget(const QString& url) const;
    void addCefViewWidget(const QString& url, CefViewWidget* p);

protected:
    CefViewWidget* getCefViewWidget(const int& browserId) const;
    virtual void onCefQuery(int browserId, qint64 frameId, const QCefQuery &query) {}
    virtual void onNewBrowser(const QString& url) {}

    std::map<const QString, QPointer<CefViewWidget>> start_url2View;
};

/// <summary>
/// Represents the customized QCefView
/// </summary>
class S_WIDGETS_EXPORT CefViewWidget : public QCefView
{
  Q_OBJECT

public:
  CefViewWidget(const QString& url, const QCefSetting* setting, QWidget* parent = 0);

  ~CefViewWidget();

  void setDelegate(QSharedPointer<CefViewDelegate> p);

  static BrowserDialog* createPopup(const QString& url, QSharedPointer<CefViewDelegate> delegate=nullptr);

protected:

  QCefView* onNewBrowser(qint64 sourceFrameId,
                                 const QString& url,
                                 const QString& name,
                                 QCefView::CefWindowOpenDisposition targetDisposition,
                                 QRect& rect,
                                 QCefSetting& settings) override;

  bool onNewPopup(qint64 sourceFrameId,
                  const QString& targetUrl,
                  QString& targetFrameName,
                  QCefView::CefWindowOpenDisposition targetDisposition,
                  const QJsonObject& popupFeatures,
                  QRect& rect,
                  QCefSetting& settings,
                  bool& disableJavascriptAccess) override;

  void onNewDownloadItem(const QSharedPointer<QCefDownloadItem>& item, const QString& suggestedName) override;

  void onUpdateDownloadItem(const QSharedPointer<QCefDownloadItem>& item) override;

private:
  QCefView * handleNewPopup(qint64 sourceFrameId,
                        const QString& url,
                        const QString& name,
                        QCefView::CefWindowOpenDisposition targetDisposition,
                        const QJsonObject& popupFeatures);

private slots:
  void onCefQueryRequest(int browserId, qint64 frameId, const QCefQuery& query);

private:
  QSharedPointer<CefViewDelegate> delegate_{nullptr};
  const QString start_url;

};

#endif // CUSTOMCEFVIEW_H
